package mail.util;

import java.io.*;
import java.util.Objects;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipException;

/**
 * @Author: Hanjiafeng
 * @Date: Created in 11:13 2019/1/22
 * @Desc: 解压缩工具
 */
public class UnZipper {

    /**
     * 解码通过流传入的gzip
     *
     * @param inputStream 传入流
     * @return 解压缩后的字符串
     */
    public static String unGzipByInputStream(InputStream inputStream) {
        BufferedReader reader = null;
        StringBuilder text = new StringBuilder();
        try {
            reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(inputStream)));
            String line;
            while ((line = reader.readLine()) != null) {
                text.append(line).append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                Objects.requireNonNull(reader).close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return text.toString();
    }

    /**
     * 解压缩字节数组
     *
     * @param gzipBytes 压缩的字节数组
     * @return 解压缩后的字节数组
     */
    public static byte[] unGzipByBytes(byte[] gzipBytes) {
        GZIPInputStream gzipInputStream = null;
        byte[] unzipBytes = gzipBytes;
        try {
            gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(gzipBytes));
            unzipBytes = gzipInputStream.readAllBytes();
        } catch (ZipException | EOFException ignore) {
            //出现解压缩错误时,不作处理,返回原始字节数组
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                Objects.requireNonNull(gzipInputStream).close();
            } catch (NullPointerException | IOException ignore) {
            }
        }
        return unzipBytes;
    }
}
